<script setup lang='ts'>
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { Search, Minus, Plus } from "@element-plus/icons-vue";

import { ElMessage } from "element-plus";
import { useEnumStore } from "@/store/enumeration"
import { equitySaveOrUpdatePost } from "@/api/equity"
import useInstance from "@/hooks/useInstance";
import BlackSelect from "@/components/customSon/blackSelect.vue";


defineOptions({
    name: "addEquAd",
});
const props = defineProps({
    supplierCodeList: {
        type: Array,
        default: () => []
    }
})
const { reductionVoucherType, expiryPeriodType, isShow } = useEnumStore()
const emit = defineEmits(["refresh"]);
const { global } = useInstance();
const dialogBasic = ref({
    title: "新建权益立减金",
    visible: false,
    width: 600,
    height: 550,
    showFooter: true,
    marginTop: "10vh",
});

const ruleFormRef = ref<FormInstance>();

const channelForm = reactive<any>({
    supplierCode: null, //  供应商编码
    reductionVoucherType: null, //  立减金类型
    reductionVoucherName: null, //  立减金名称
    reductionVoucherAmount: null, //  立减金额度
    expiryPeriod: null, //  过期期限
    supplierReductionVoucherCode: null, //  供应商立减金编码

    expiryPeriodType: null, //  过期期限类型
    remainderQuota: null, //  剩余配额
    enabled: null, //  是否启用
    extInfo: [
        {
            key: null,
            value: null,
        },
    ],
});
const rules = reactive<FormRules>({
    enabled: [
        {
            required: true,
            trigger: "blur",
            message: "请选择是否启用",
        },
    ],
    remainderQuota: [
        {
            required: true,
            trigger: "blur",
            message: "请输入剩余配额",
        },
    ],
    expiryPeriodType: [
        {
            required: true,
            trigger: "blur",
            message: "请选择过期期限类型",
        },
    ],
    expiryPeriod: [
        {
            required: true,
            trigger: "blur",
            message: "请输入过期期限",
        },
    ],
    reductionVoucherAmount: [
        {
            required: true,
            trigger: "blur",
            message: "请输入立减金额度",
        },
    ],
    reductionVoucherName: [{
        required: true,
        trigger: "blur",
        message: "请输入立减金名称",
    },],
    supplierReductionVoucherCode: [{
        required: true,
        trigger: "blur",
        message: "请输入供应商立减金编码",
    },],
    supplierCode: [
        {
            required: true,
            trigger: "blur",
            message: "请选择供应商编码",
        },
    ],
    reductionVoucherType: [
        {
            required: true,
            trigger: "blur",
            message: "请选择立减金类型",
        },
    ]
});
//显示弹框
const show = (type: string, row?: any) => {
    dialogBasic.value.visible = true;
    if (type === "add") {
        dialogBasic.value.title = "新建权益立减金";
        dialogBasic.value.height = 500;
        global.$resetForm(ruleFormRef.value, channelForm);
        channelForm.extInfo = [
            {
                key: null,
                value: null
            }
        ]
        resetForm();
    } else {
        dialogBasic.value.height = 550;

        global.$resetForm(ruleFormRef.value, channelForm);
        dialogBasic.value.title = "编辑权益立减金";
        global.$objCopy(channelForm, row);

        const arr = JSON.parse(row.extInfo)
        console.log(arr);
        
        if (arr && Object.keys(arr).length > 0) {
            channelForm.extInfo = []
           
            Object.keys(arr).forEach(item => {
                console.log(typeof arr[item]);
                
                channelForm.extInfo.push({
                    key: item,
                    value: arr[item]
                })
            })
        } else {
            channelForm.extInfo = [
                {
                    key: null,
                    value: null
                }
            ]
        }
    }
};
const onClose = () => {
    dialogBasic.value.visible = false;
    channelForm.extInfo = [
        {
            key: null,
            value: null
        }
    ]
    resetForm();
};
const onConfirm = async () => {
    //  [{bankCode:BC,bankName:中国银行,productCode:3011},{bankCode:CBC,bankName:中国建设银行,productCode:3010},{bankCode:ABC,bankName:中国农业银行,productCode:3009},{bankCode:CMBC,bankName:中国招商银行,productCode:3008},{bankCode:ICBC,bankName:中国工商银行,productCode:1931}]
    await ruleFormRef.value?.validate(async (isOk) => {
        if (isOk) {
            const arr: any = {}
       
            channelForm.extInfo &&   channelForm.extInfo.forEach((item: any) => {
                if (item.key) {
                    arr[item.key] = item.value
                }
            })

            const newArr = Object.keys(arr).length == 0 ? "{}" : JSON.stringify(arr)
            // 删除一个数据
            if(channelForm.id){
                delete  channelForm.remainderQuota 
            }
            const res = await equitySaveOrUpdatePost({ ...channelForm, extInfo: newArr });
            if (res.code == 20000) {
                ElMessage({
                    type: "success",
                    message: channelForm.id ? "立减金编辑成功" : "立减金新增成功",
                });
            }
            emit("refresh");
            onClose();
        } else {
            ElMessage({
                type: "error",
                message: channelForm.id
                    ? "立减金编辑失败 请重试！"
                    : "立减金新增失败 请重试！",
            });
        }
    });
};
const btnAdd = () => {
    channelForm.extInfo.push({
        key: null,
        value: null,
    });
};
const removeDomain = (item: any) => {
    const index = channelForm.extInfo.indexOf(item)
    if (index !== -1) {
        channelForm.extInfo.splice(index, 1)
    }
}
const resetForm = () => {
    ruleFormRef.value?.resetFields();
};

defineExpose({
    show,
});
</script>

<template>
    <SysDialog :title="dialogBasic.title" :width="dialogBasic.width" :height="dialogBasic.height"
        :show-footer="dialogBasic.showFooter" :visible="dialogBasic.visible" :margin-top="dialogBasic.marginTop"
        @on-close="onClose" @on-confirm="onConfirm">
        <template v-slot:content>
            <div class="channel-form">
                <el-form ref="ruleFormRef" :model="channelForm" :rules="rules" label-width="130px" class="demo-ruleForm"
                    status-icon>
                    <el-form-item label="供应商编码" prop="supplierCode">
                        <BlackSelect v-model:select-value="channelForm.supplierCode" :multiple="false"
                            :options="supplierCodeList"></BlackSelect>
                    </el-form-item>
                    <el-form-item label="立减金名称" prop="reductionVoucherName">
                        <el-input v-model="channelForm.reductionVoucherName" />
                    </el-form-item>
                    <el-form-item label="供应商立减金编码" prop="supplierReductionVoucherCode">
                        <el-input v-model="channelForm.supplierReductionVoucherCode" />
                    </el-form-item>
                    <el-form-item label="立减金类型" prop="reductionVoucherType">
                        <my-select v-model:select-value="channelForm.reductionVoucherType" :multiple="false"
                            :options="reductionVoucherType"></my-select>
                    </el-form-item>
                    <el-form-item label="立减金额度" prop="reductionVoucherAmount">
                        <el-input v-model.number="channelForm.reductionVoucherAmount" />
                    </el-form-item>
                    <el-form-item label="剩余配额" prop="remainderQuota" v-if="!channelForm.id">
                        <el-input v-model.number="channelForm.remainderQuota" />
                    </el-form-item>

 
                    <el-form-item label="过期期限类型" prop="expiryPeriodType">
                        <BlackSelect v-model:select-value="channelForm.expiryPeriodType" :multiple="false"
                            :options="expiryPeriodType"></BlackSelect>
                    </el-form-item>
                    <el-form-item label="过期期限" prop="expiryPeriod">
                        <AddInput v-model.number:model-value="channelForm.expiryPeriod"></AddInput>
                    </el-form-item>
                    <el-form-item label="是否启用" prop="enabled">
                        <my-select v-model:select-value="channelForm.enabled" :multiple="false"
                            :options="isShow"></my-select>
                    </el-form-item>

                    <el-form-item v-for="(domain, index) in channelForm.extInfo" :key="index"
                        :label="'信息扩展' + (index + 1)">
                        <el-row style="width: 100%" justify="space-around">
                            <el-col :span="6">
                                <el-input v-model="domain.key" placeholder="请输入value"
                                    :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"></el-input>
                            </el-col>
                            <el-col :span="15">
                                <el-input v-model="domain.value" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                                    placeholder="请输入value" clearable></el-input>                                    
                            </el-col>
                            <el-col :span="2">
                                <el-button type="danger" style="margin-top: 12px" size="small"
                                    @click="removeDomain(domain)" :icon="Minus" />
                            </el-col>
                        </el-row>
                    </el-form-item>

                    <el-form-item label="添加信息扩展">
                        <el-button type="primary" @click="btnAdd" :icon="Plus" style="width: 100%" />
                    </el-form-item>
                </el-form>
            </div>

        </template>
    </SysDialog>
</template>

<style lang='scss' scoped>
.channel-form {
    height: 600px;
    overflow: auto;
}
</style>
